<template>
  <div class="mainpg">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="mainor_form">
          <div class="mainor_te">
            <router-link to="/user/quotation/add/add" class="mainor_tea"
              >创建报价单</router-link
            >
            <el-button @click="importDialog">导入报价单</el-button>
          </div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="用户名称" prop="name">
              <el-input
                v-model.trim="form.name"
                placeholder="用户名称/编码/手机"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="单号" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="单号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item class>
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="$refs['userListFrom'].resetFields()"
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList"
                :loading="listLoading"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_table" style="min-height: 670px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            highlight-current-row
          >
            <el-table-column
              label="单号"
              prop="order_sn"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="开始时间" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ parseTime(scope.row.start_time, "{y}-{m}-{d}") }}
              </template>
            </el-table-column>
            <el-table-column label="结束时间" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ parseTime(scope.row.end_time, "{y}-{m}-{d}") }}
              </template>
            </el-table-column>
            <el-table-column
              label="用户"
              prop="uids"
              :show-overflow-tooltip="true"
              min-width="300"
            />
            <el-table-column
              label="状态"
              prop="title"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <div class="main_link">
                  <el-link type="info" v-if="scope.row.status == 0"
                    >已取消</el-link
                  >
                  <el-link type="success" v-else-if="scope.row.status == 1"
                    >正常</el-link
                  >
                  <el-link type="danger" v-else>已失效</el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              prop="remark"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="管理操作"
              :render-header="renderHeader2"
              fixed="right"
              width="240"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <router-link :to="'/user/quotation/see/' + scope.row.id">
                  <el-link type="success">查看</el-link>
                </router-link>
                <el-link v-repeatClick @click="handleExport(scope.row)"
                  >导出</el-link
                >
                <router-link
                  :to="'/user/quotation/add/' + scope.row.id"
                  v-if="scope.row.status == 1 || scope.row.status == -1"
                >
                  <el-link type="warning">复制</el-link>
                </router-link>
                <router-link
                  :to="'/user/quotation/edit/' + scope.row.id"
                  v-if="scope.row.status == 0"
                >
                  <el-link type="primary">编辑</el-link>
                </router-link>
                <template>
                  <el-dropdown>
                    <el-link type="danger" class="el-dropdown-link"
                      >更多</el-link
                    >
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <el-link
                          style="color: #118ab2"
                          @click="synchronousOrder(scope.row.id, scope.row)"
                          >同步</el-link
                        ></el-dropdown-item
                      >
                      <el-dropdown-item>
                        <el-link
                          v-if="scope.row.status == 1"
                          @click="(id = scope.row.id), cancel(scope.$index)"
                          >取消</el-link
                        >
                      </el-dropdown-item>
                      <!-- <el-dropdown-item>
                        <router-link
                          :to="'/user/quotation/edit/' + scope.row.id"
                          v-if="scope.row.status == 0"
                        >
                          <el-link type="primary">编辑</el-link>
                        </router-link></el-dropdown-item
                      > -->
                      <el-dropdown-item>
                        <el-link
                          type="danger"
                          @click="(id = scope.row.id), delet(scope.$index)"
                          v-if="scope.row.status == 0 || scope.row.status == -1"
                          >删除</el-link
                        ></el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <el-pagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
      <!-- 订单导入 -->
      <el-dialog
        title="周期报价导入"
        :visible.sync="importbuVisible"
        class="main_dialog dialog700 importbu"
      >
        <div class="importbu_p">
          <h3>导入说明：</h3>
          <p>1.注意使用红色字体标注的必填字段,不填或错填将导致导入失败。</p>
          <p>2.导入文件仅支持xlsx格式,大小不超过2M ,数据不超过2000行。</p>
          <p>3.导入文件不能包含“合并单元格”，否则无法导入。</p>
          <p>
            4.导入时碰到数据不正确的行，系统会跳过错误的行继续执行未完成的行。
          </p>
        </div>
        <div class="importbu_an box">
          <el-button class="marginRight10" @click="downTemplate"
            >下载模板</el-button
          >
          <el-upload
            class="upload-demo"
            :action="user_cycle_export"
            :on-success="importSuccess"
            :on-error="importerr"
            :show-file-list="false"
            :data="import_params"
            :headers="import_header"
          >
            <el-button size="small" type="primary" @click="handleUpload"
              >点击上传</el-button
            >
          </el-upload>

          <p v-if="import_file_name ? true : false">
            上传文件名：{{ import_file_name }}
          </p>
        </div>
        <div class="import_process" v-if="percentShow">
          <div class="progress">
            <el-progress
              :text-inside="true"
              :stroke-width="20"
              :percentage="percent"
              color="#19B098"
            ></el-progress>
          </div>
          <div class="notice" v-if="percentShow">
            <div class="importtips">
              <p class="success" v-if="percent == 100">周期报价导入结束</p>
              <div v-for="(item, index) in reverseSum" :key="index">
                <p v-if="item.type == 2" :key="index" class="fail">
                  {{ item.name }}
                </p>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button :disabled="cancelDisabled" @click="importbuVisible = false"
            >取 消</el-button
          >
        </div>
      </el-dialog>

      <!-- 批量同步 -->
      <el-dialog
        :title="'已选择' + arrlist.length + '个商品，同步中！'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="close"
        :visible.sync="addedFormVisible"
        class="main_dialog dialog450"
      >
        <div class="notices">
          <el-progress
            :text-inside="true"
            :stroke-width="15"
            :percentage="datapercent"
            status="success"
            color="#19B098"
          ></el-progress>
          <div class="progress_list">
            <template v-for="(datalist, index) in reversedata">
              <template v-if="index < 5">
                <p v-if="datalist.type == 1" :key="index">
                  商品{{ datalist.name }}，同步已成功
                </p>
                <p v-else class="progress_list_red" :key="index">
                  商品{{ datalist.name }}，同步失败
                </p>
              </template>
            </template>
            <p class="progress_list_su">
              同步已经完成请关闭弹框!
            </p>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  cycle_index,
  cycle_delete,
  cycle_cancel,
  cycle_synchronousOrder,
  user_import_model,
  cycle_export
} from "@/api/user/userQuotation";
import { parseTime, exportMethod } from "@/utils/index";
import { user_cycle_export } from "@/api/currency";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { mapGetters } from "vuex";

export default {
  components: {},
  data() {
    return {
      // 时间
      parseTime,
      user_cycle_export,
      exportMethod,
      // 搜索
      form: {
        name: "",
        order_sn: ""
      },
      // 分页
      current: {
        page: 1,
        per_page: 20
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: {
          data: []
        }
      },
      listLoading: false,
      // 订单导入
      importbuVisible: false,
      import_file_name: "",
      import_params: {},
      percent_gs: 0,
      percent: 0,
      percentShow: false,
      percent_list: [],
      importArrLength: 1,
      cancelDisabled: false,
      // 批量同步
      datalist: [],
      addedFormVisible: false,
      datanum: 0,
      datacount: 0,
      datapercent: 0,
      arrlist: []
    };
  },
  computed: {
    ...mapGetters(["avatar", "token"]),
    reverseSum() {
      return this.percent_list;
    },
    reversedata() {
      return this.datalist.reverse();
    },
    import_header() {
      return {
        "X-Token": this.token,
        Authorization: this.token
      };
    }
  },
  methods: {
    close() {
      this.percent = 0;
      this.percent_gs = 0;
      this.datalist = [];
      this.cycle_index();
    },
    renderHeader2(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h("div", [
        // h即为cerateElement的简写
        // 在div里面插入span
        h("span", {
          // 表示内容
          domProps: {
            innerHTML: column.label
          },
          on: {
            click: () => {}
          },
          style: {
            marginLeft: "18px"
          }
        }),
        h(
          "el-tooltip",
          {
            // 表示属性
            attrs: {
              effect: "dark",
              content: "周期内含有报价单中商品的订单，单价同步为报价。",
              placement: "top"
            }
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg"
            })
          ]
        )
      ]);
    },
    synchronousOrder(id, row) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { id: id }
      );
      this.arrlist.push(row);

      cycle_synchronousOrder(data)
        .then(res => {
          if (res.errcode == 0) {
            this.$message.success("同步成功");
          } else {
            this.$message.error(res.errmsg);
          }
        })
        .catch(() => {});
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.cycle_index();
    },
    // 删除
    delet(index) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        { id: this.id }
      );
      this.$confirm("是否删除报价?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          cycle_delete(data).then(res => {
            if (res.errcode == 0) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.list.list.data.splice(index, 1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 取消
    cancel(index) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        { id: this.id }
      );
      this.$confirm("是否取消报价?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          cycle_cancel(data).then(res => {
            if (res.errcode == 0) {
              this.$message({
                message: "取消成功",
                type: "success"
              });
              this.list.list.data[index].status = 0;
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.cycle_index();
    },
    changePage(page) {
      this.current.page = page;
      this.cycle_index();
    },
    // 列表
    cycle_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        JSON.parse(JSON.stringify(this.form)),
        this.current
      );
      cycle_index(data).then(res => {
        this.listLoading = false;
        if (res.errcode == 0) {
          res.data.list.data.map(e => {
            e.uids = e.members.map(p => p.nickname).join("，");
          });
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 下载模板
    downTemplate() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name
      );
      user_import_model(data).then(res => {
        this.exportMethod(res, "周期报价导入模板");
      });
    },
    // 导入订单
    importDialog() {
      this.import_file_name = "";
      this.percent_gs = 0;
      this.percent = 0;
      this.percentShow = false;
      this.percent_list = [];
      this.importArrLength = 1;
      this.cancelDisabled = false;
      this.importbuVisible = true;
    },

    importerr(err, file, fileList) {
      this.$message.error("上传失败");
    },
    importSuccess(response, file, fileList) {
      if (response.code == 100) {
        this.$message.warning(response.msg);
        return;
      }
      this.import_file_name = file.name;
    },
    handleUpload() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name
      );
      this.import_params = data;
    },
    // 导出
    handleExport(row) {
      let data = {
        id: row.id
      };
      cycle_export(data).then(res => {
        this.exportMethod(res, "周期报价");
      });
    }
  },
  created() {
    // 列表
    this.cycle_index();
  },
  mounted() {
    window.Echo.channel("batchImportCycle." + this.avatar.company_id).listen(
      "BathImportCycleEvent",
      e => {
        this.cancelDisabled = true;
        this.importArrLength = e.notice.count;
        this.percentShow = true;
        if (e.notice.errcode == 0) {
          this.percent_list.push({
            num: this.percent,
            type: 1,
            name: e.notice.msg
          });
        } else if (e.notice.errcode == 100) {
          this.percent_list.push({
            num: this.percent,
            type: 2,
            name: e.notice.msg
          });
        }
        this.percent_gs = parseInt(this.percent_gs) + 1;
        if ((this.percent_gs / this.importArrLength) * 100 >= 100) {
          this.percent = 100;
          this.cancelDisabled = false;
          return;
        }
        this.percent =
          this.percent_gs / this.importArrLength
            ? parseInt((this.percent_gs / this.importArrLength) * 100)
            : 0;
      }
    );

    window.Echo.channel("cyclePrice." + this.avatar.company_id).listen(
      "CyclePriceEvent",
      e => {
        console.log(e, "eeeee");
        this.addedFormVisible = true;
        this.datanum = e.data.num;
        this.datacount = e.data.count;
        console.log(this.arrlist);

        if ((this.datanum / this.datacount) * 100 >= 100) {
          this.datapercent = 100;
          return;
        }
        this.datapercent = this.datanum / datacount ? parseInt((this.datanum / datacount) * 100) : 0;

        if (e.data.msg == "ok") {
          this.datalist.push({
            num: e.data.num,
            type: 1,
            name: e.data.count
          });
        } else {
          this.datalist.push({
            num: this.datapercent,
            type: 2,
            name: e.data.num
          });
        }
      }
    );
  }
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 220px);
}
// 导入进度条
.import_process {
  width: 100%;
}

.progress {
  padding: 15px 40px 15px 0;
}
.notice {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding-right: 40px;
  .importtips {
    overflow-y: auto;
    width: 100%;
    height: 84px;
    height: 84px;
    background: #ffffff;
    border: 1px solid #d8d8d8;
    padding: 10px 15px;
    .fail {
      color: #ff5a5a;
      line-height: 1.2;
      font-size: 12px;
    }
    .success {
      color: #19b098;
      line-height: 1.2;
      font-size: 12px;
    }
  }
}
.importbu_in {
  /deep/ .el-input__inner {
    padding-right: 0;
  }
}

.notices {
  .progress_list {
    padding: 15px 0;
  }
}
</style>
